<script setup lang="tsx">
import { ref } from 'vue';
import { NDivider } from 'naive-ui';
import { fetchBatchDeleteTenant } from '@/service/api/system/tenant';
import { fetchGetWithdrawList, fetchToWithdraw } from '@/service/api/business/withdraw';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useDict } from '@/hooks/business/dict';
import DictTag from '@/components/custom/dict-tag.vue';
import { $t } from '@/locales';
import ButtonIcon from '@/components/custom/button-icon.vue';
import TenantOperateDrawer from './modules/tenant-operate-drawer.vue';
import TenantSearch from './modules/tenant-search.vue';

defineOptions({
  name: 'TenantList'
});

useDict('sys_normal_disable');

const appStore = useAppStore();
const { hasAuth } = useAuth();
const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetWithdrawList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    username: null,
    withdrawTime: null,
    status: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64
    },
    {
      key: 'id',
      title: '编号',
      align: 'center',
      minWidth: 80
    },
    {
      key: 'username',
      title: '代理人',
      align: 'center',
      minWidth: 80
    },
    {
      key: 'withdrawType',
      title: '提现方式',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'withdrawAmount',
      title: '提现金额',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'handleFee',
      title: '手续费',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'arriveAmount',
      title: '实际到账',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'withdrawTime',
      title: '提现时间',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'status',
      title: '提现状态',
      align: 'center',
      minWidth: 120,
      render(row) {
        return <DictTag size="small" value={row.status} dictCode="sys_normal_disable" />;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 180,
      render: row => {
        // 判断是否应该禁用按钮：已提现(status=1)或已有到账金额(arriveAmount>0)
        const isDisabled = row.status >= 1;

        const withdrawBtn = () => {
          return (
            <ButtonIcon
              type="primary"
              text
              icon="material-symbols:money-outline"
              tooltipContent="管理员打款"
              disabled={isDisabled}
              popconfirmContent={isDisabled ? '' : '确认要执行打款操作吗？'}
              onPositiveClick={() => handleWithdraw(row.id)}
            />
          );
        };

        const buttons = [];
        if (hasAuth('business:withdraw:pay')) buttons.push(withdrawBtn());

        return (
          <div class="flex-center gap-8px">
            {buttons.map((btn, index) => (
              <>
                {index !== 0 && <NDivider vertical />}
                {btn}
              </>
            ))}
          </div>
        );
      }
    }
  ]
});

const { drawerVisible, operateType, editingData, handleAdd, checkedRowKeys, onBatchDeleted } = useTableOperate(
  data,
  getData
);

// 提现操作加载状态
const withdrawLoading = ref(false);

async function handleBatchDelete() {
  const { error } = await fetchBatchDeleteTenant(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

async function handleWithdraw(id: number) {
  withdrawLoading.value = true;
  try {
    const { error } = await fetchToWithdraw({ id });
    if (error) {
      window.$message?.error('提现操作失败');
      return;
    }
    window.$message?.success('提现操作成功');
    // 刷新数据
    await getData();
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
  } catch (e) {
    window.$message?.error('操作异常，请稍后重试');
  } finally {
    withdrawLoading.value = false;
  }
}

</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <TenantSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard title="提现请求列表" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-add="false"
          :show-delete="false"
          :show-export="hasAuth('system:tenant:export')"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        ></TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <TenantOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
